package cn.ainit.sys.framework.upload;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import cn.ainit.sys.menu.SessionCont;
import cn.ainit.sys.utils.UUID32;

@Service
public class UploadServiceImpl implements UploadService{
	private UploadDao uploadDao;
	
	@Resource
	public void setUploadDao(UploadDao uploadDao) {
		this.uploadDao = uploadDao;
	}
	
	@Override
	public List<Map<String, Object>> loadAllImgs(String dsId, String clnName,
			String pkValue) throws Exception {
		return this.uploadDao.loadAllImgs(dsId,clnName,pkValue);
	}
	
	@Override
	public boolean saveImgPath(SysUploadInfo uploadInfo) throws Exception {
		return this.uploadDao.saveImgPath(uploadInfo);
	}
	
	@Override
	public boolean saveFiles(SysUploadInfo uploadInfo) throws Exception {
		return this.uploadDao.saveFiles(uploadInfo);
	}
	
	@Override
	public String saveFilesToDb(SysUploadInfo uploadInfo) throws Exception {
		return this.uploadDao.saveFilesToDb(uploadInfo);
	}
	
	@Override
	public SysFilesList getFileList(SysFilesList fileList) throws Exception {
		return this.uploadDao.getFileList(fileList);
	}
	
	@Override
	public boolean delFile(SysUploadInfo delFile) throws Exception {
		return this.uploadDao.delFile(delFile);
	}
	
	@Override
	public SysUploadInfo downFile(SysUploadInfo downFile) throws Exception {
		return this.uploadDao.downFile(downFile);
	}
	
	@Override
	public Integer getWCount(String pkValue) throws Exception {
		return this.uploadDao.getWCount(pkValue);
	}
	
	@Override
	public List<WeiBoObj> loadWeiBo(String pkValue) throws Exception {
		return this.uploadDao.loadWeiBo(pkValue);
	}
	
	
	/**
	 * 删除临时文件里的图片
	 */
	@Override
	public void deletetemporaryPicture(
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
		String temporaryFolder = request.getParameter("dsId");
		String uid=(String)session.getAttribute(SessionCont.uid);
		String ctxPath = request.getSession().getServletContext().getRealPath("/");
		String name = request.getParameter("name");
		if(name.length()>0) 
		{
			name += name.substring(name.lastIndexOf("."));
			String folder = "UploadFiles\\temporary\\"+temporaryFolder+"-"+uid+"\\"+name;
			File file = new File(ctxPath + folder);
			if(file.exists())
			{
				file.delete();
			}
		}
		else{
			String folder =  "UploadFiles\\temporary\\"+temporaryFolder+"-"+uid;
			// 读取临时文件夹并删除里面所有图片 //
			File file = new File(ctxPath + folder);
			if (file.exists()) {
				File[] f = file.listFiles();
				if(f.length>0)
				{
					for (int i = 0; i < f.length; i++) {
						f[i].delete();
					}
				}
			}
		}
	}
	
	
	

	/****
	 * 点击上传的时候 直接把图片存到临时文件夹
	 */
	@Override
	public String uploadPicture(MultipartFile fileImg,String dsId,HttpServletRequest request,
			HttpServletResponse response, HttpSession session) {
		String fName = fileImg.getOriginalFilename();
		String temporaryFolder = request.getParameter("dsId");
		String clnname = request.getParameter("colnName");
		temporaryFolder=dsId;
		if(dsId==null||"".equals(temporaryFolder)){
			System.out.println("==============#UploadServiceImpl 194 上传图片的dsId 传入有误，请修改");
		}
		if(temporaryFolder.contains(";"))
		{
			temporaryFolder = temporaryFolder.split(";")[0];
		}
		String error="";
		//判断图片name是否包含非法字符
		String regEx="!|！|@|◎|#|＃|(\\$)|￥|%|~|`|·|％|(\\^)|……|(\\&)|※|(\\*)|×|(\\()|（|(\\))|）|——|(\\+)|＋|(\\|)|§";
		Pattern pattern  = Pattern.compile(regEx);
		Matcher matcher=pattern.matcher(fName); 
		if(matcher.find())
		{
			error = "NamingError";
			return error;
		}
		String pkValue = UUID32.newGuid();
		fName = clnname+"-"+pkValue+"-"+fName;
		try {
			String ctxPath = request.getSession().getServletContext().getRealPath("/");
			String uid=(String)session.getAttribute(SessionCont.uid);
			//个人临时文件夹
			String folder =  "UploadFiles\\temporary\\"+temporaryFolder+"-"+uid;
			File file = new File(ctxPath + folder);
			//正式文件夹
			String perFileFolder =  "UploadFiles\\permanent";
			File perFile = new File(ctxPath + perFileFolder);
			if (!file.exists()) {// 如果文件夹不存在，则创建该文件夹
				file.mkdir();
			}
			// /// 页面图片上传到临时文件夹 ////
			Boolean isDouble=true;
			//与临时图片判重
			File[] files = file.listFiles();
//			for (int i = 0; i < files.length; i++) {
//				if(fName.equals(files[i].getName())){
//					error = fName;
//					isDouble = false;
//				}
//			}
//			//与正式图片判重
//			File[] perFiles = perFile.listFiles();
//			for (int i = 0; i < perFiles.length; i++) {
//				if(fName.equals(perFiles[i].getName())){
//					error = fName;
//					isDouble = false;
//				}
//			}
			if(isDouble)
			{
				InputStream in = fileImg.getInputStream();
				OutputStream out = new FileOutputStream(new File(ctxPath + folder
						+ "\\" + fName));// 指定要写入的图片
				int n = 0;// 每次读取的字节长度
				byte[] bb = new byte[1024];// 存储每次读取的内容
				while ((n = in.read(bb)) != -1) {
					out.write(bb, 0, n);// 将读取的内容，写入到输出流当中
				}
				out.close();// 关闭输入输出流
				in.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(error.length()>0)
		{
			return error;
		}
		else{
			return "success";
		}
	}
	
	@Override
	public String deletedPictureById(HttpServletRequest request,
			HttpServletResponse response, HttpSession session) {
		return uploadDao.deletedPictureById(request,response,session);
		 
	}

}
